package cn.pconline.autoclub.web.price;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.pconline.autoclub.config.SystemConfig;
import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubPetrol;
import cn.pconline.autoclub.service.ClubService;
import cn.pconline.autoclub.service.MemberService;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.autoclub.util.EncodeUtils;
import cn.pconline.autoclub.util.Pager;
import cn.pconline.autoclub.util.WebUtils;
import cn.pconline.autoclub.util.WhoisUtil;
import cn.pconline.autoclub.util.app.AppControllerStatic;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author zhouruxuan
 * @date 2014年12月1日 上午11:25:47
 */
@Controller
@RequestMapping(value = "/priceapi")
public class PriceController {
	
	@Autowired
	private ClubService clubService;
	@Autowired
	private SystemConfig systemConfig;
	@Autowired
	private MemberService memberService;
	@Autowired
	private PetrolService petrolService;
	
	private static final int DEF_CLUBS_NUM_5 = 5;//默认返回5个车友会
	private static final int DEF_CLUBS_NUM_3 = 3;//默认返回3个车友会
	private static final int DEF_TONGCHENG_CLUBS_NUM = 4;//默认返回4个同城车友会
    private static final String V1_VERSION = "v1.0";//当前接口版本号1.0
    private static final String V1_VERSION_LATEST = "v1.0(latest)";// 当前接口版本号1.0为最新的版本
	
	/**
	 * 汽车网车友会报价库露出接口
	 * 
	 * 排名即是指“活跃度”
	 * 1.默认出当前车系的车友会，按照排名先后露出，最多5个
	 * 2.当前车系不足5个的，补当前品牌的车友会，最多5个，车系的优先排前面，品牌的排后面
	 * 3.当前品牌不足5个车友会的时候（至少还有1个），下面会出现推荐车友会，缺几个就补几个，最多露出5个
	 * 4.推荐车友会的露出，以IP作为识别，按地区排名最前的来露出，优先城市，然后是省份，最后是全国
	 * 5、如果品牌下面一个车友会也没有，则顶部露出创建车友会的按钮
	 * 6、下面出该地区下面排名最前的4个地区车友会
	 * 
	 * @param request
	 * @param response
	 */
	@ResponseBody
	@RequestMapping(value = "/1.0/club/listTopClubs.do", method = RequestMethod.GET)
	public void listTopClub(HttpServletRequest request, HttpServletResponse response) {
		WebUtils.setEncoding(request, response);
		//获取相关参数
		String callback = WebUtils.param(request, AppControllerStatic.APP_API_PARA_CALLBACK, "");
        int xssEncode = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_XSSENCODE, 0);
        long brandId = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_BRANDID, 0);
        long seriesId = WebUtils.paramInt(request, AppControllerStatic.APP_API_PARA_SERIESID, 0);
        String ip = WebUtils.param(request, "ip", "");
        
        JSONObject jsonObject = new JSONObject();
        
        //非空参数检查
        if(seriesId == 0) {
        	AppControllerStatic.printErrorMsg(response, "非法参数seriesId", jsonObject, callback, V1_VERSION_LATEST);
        	return;
        }
        if(brandId == 0) {
        	AppControllerStatic.printErrorMsg(response, "非法参数brandId", jsonObject, callback, V1_VERSION_LATEST);
        	return;
        }
        
        //获取省市ID
        if(StringUtils.isBlank(ip)) {
        	AppControllerStatic.printErrorMsg(response, "非法参数ip", jsonObject, callback, V1_VERSION_LATEST);
        	return;
        }
        JSONObject region;
        try {
        	region = WhoisUtil.getProvinceAndCity(ip);
        } catch(Exception exception) {
        	AppControllerStatic.printErrorMsg(response, "ip地址不正确", jsonObject, callback, V1_VERSION_LATEST);
        	return;
        }
        long provinceId = region.get("areaCode").toString().equals("null") ? 0 : region.getIntValue("areaCode");
        long cityId = region.get("cityCode").toString().equals("null") ? 0 : region.getIntValue("cityCode");
        
        //返回的车友会列表
        List<Club> returnClubs = new ArrayList<Club>();
        //返回推荐车友会列表
        List<Club> isRecommendClubs = new ArrayList<Club>();
        //根据车系查找车友会，按照排名先后露出，最多5个
        List<Club> seriesClubs = clubService.getListBySeriesId(seriesId, 1, DEF_CLUBS_NUM_5);
        returnClubs.addAll(seriesClubs);
        //如果根据车系查找的车友会不足5个，查找当前品牌下的车友会
        if(returnClubs.isEmpty() || returnClubs.size() < DEF_CLUBS_NUM_5) {
        	List<Club> brandClubs = clubService.listClubByBrandIdExceptSeriesId(brandId, seriesId, 1, DEF_CLUBS_NUM_5 - returnClubs.size());
        	returnClubs.addAll(brandClubs);
        }
        
        //1:有品牌车友会；0：没有品牌车友会
        int isBrandclub = 1;
       
        //如果品牌没有车友会，显示4个同城车友会
        if(returnClubs.isEmpty()) {
        	isBrandclub = 0;
        	//查找当前同城车友会
        	List<Club> cityClubs = clubService.getListByCityIdProvinceId(cityId, provinceId, 1, DEF_TONGCHENG_CLUBS_NUM);
        	returnClubs.addAll(cityClubs);
            //查找当前同省车友会
        	if(returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
        		List<Club> proviceClubs = clubService.listClubByProvinceIdExceptCityId(provinceId, cityId, 1, DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
        		returnClubs.addAll(proviceClubs);
        	}
        	//查找全国车友会
        	if(returnClubs.size() < DEF_TONGCHENG_CLUBS_NUM) {
        		List<Club> countryClubs = clubService.getListByCityIdProvinceId(0, 0, 1, DEF_TONGCHENG_CLUBS_NUM - returnClubs.size());
        		returnClubs.addAll(countryClubs);
        	}
        	
        } else if(returnClubs.size() < DEF_CLUBS_NUM_5) {//设置品牌车友会和推荐车友会
        	//查找当前同城车友会
        	List<Club> cityClubs = clubService.getListByCityIdProvinceId(cityId, provinceId, 1, DEF_CLUBS_NUM_5 - returnClubs.size());
        	isRecommendClubs.addAll(cityClubs);
            //查找当前同省车友会
        	int totalSize = returnClubs.size() + isRecommendClubs.size();
        	if( totalSize < DEF_CLUBS_NUM_5) {
        		List<Club> proviceClubs = clubService.listClubByProvinceIdExceptCityId(provinceId, cityId, 1, DEF_CLUBS_NUM_5  - totalSize);
        		isRecommendClubs.addAll(proviceClubs);
        	}
        	//查找全国车友会
        	totalSize = returnClubs.size() + isRecommendClubs.size();
        	if( totalSize < DEF_CLUBS_NUM_5) {
        		List<Club> countryClubs = clubService.getListByCityIdProvinceId(0, 0, 1, DEF_CLUBS_NUM_5 - totalSize);
        		isRecommendClubs.addAll(countryClubs);
        	}
        }

    	//组装品牌车友会属性列表
        JSONArray jsonArray = new JSONArray();
        for(Club club : returnClubs) {
        	JSONObject json = new JSONObject();
        	json.put("clubId", club.getClubId());
            json.put("name", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
            json.put("logo", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
            //会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            //1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 0);
            
            jsonArray.add(json);
        }
        
        //组装推荐车友会属性列表
        for(Club club : isRecommendClubs) {
        	JSONObject json = new JSONObject();
        	json.put("clubId", club.getClubId());
            json.put("name", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
            json.put("logo", xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
            json.put("url", systemConfig.getRoot() + "/" + club.getClubUrl() + "/");
            //会员数
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            //1：是推荐车友会；0：不是推荐车友会
            json.put("isRecommend", 1);
            
            jsonArray.add(json);
        }
        
        //返回车友会列表
        jsonObject.put("data", jsonArray);
        //1:有品牌车友会；0：没有品牌车友会
        jsonObject.put("isBrandClub", isBrandclub);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, V1_VERSION_LATEST);
	}
	
	/**
     * 车友会所有车系id
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/getAllClubSeries.do", method = RequestMethod.GET)
    public void getAllClubSeries(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //获取相关参数
        String callback = WebUtils.param(request, AppControllerStatic.APP_API_PARA_CALLBACK, "");
        List<Long> seriesIds = clubService.getAllClubSeriesIds();
        
        JSONObject jsonObject = new JSONObject();
        if(seriesIds != null) {
            jsonObject.put("seriesIds", seriesIds);
        } else {
            jsonObject.put("seriesIds", "[]");
        }
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback, V1_VERSION_LATEST);
    }
    
    /**
     * 提供3个车系车友会
     * 如果没有这车系的返回空数组
     * 补位明规则：城市--》省--》全国
     * 
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/1.0/club/listTopClubsBySeriesId.do", method = RequestMethod.GET)
    public void listTopClubsBySeriesId(HttpServletRequest request, HttpServletResponse response) {
        WebUtils.setEncoding(request, response);
        //缓存1小时
        //WebUtils.setCacheHeader(response, 3600);
        //获取相关参数
        String callback = AppControllerStatic.paramCallback(request);
        int xssEncode = AppControllerStatic.paramXssEncode(request);
        long seriesId = AppControllerStatic.paramSeriesId(request);
        long provinceId = AppControllerStatic.paramProvinceId(request);
        long cityId = AppControllerStatic.paramCityId(request);
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        // 非空参数检查
        if (seriesId == 0) {
            AppControllerStatic.printErrorMsg(response, "非法参数seriesId",
                    jsonObject, callback, AppControllerStatic.V1_VERSION_LATEST);
            return;
        }
        
        // 返回的车友会列表
        List<Club> returnClubs = new ArrayList<Club>();
        List<Club> cityClubs = new ArrayList<Club>();
        List<Club> proClubs = new ArrayList<Club>();
        List<Club> counClubs = new ArrayList<Club>();
        
        //获取市的车系车友会
        Pager<Club> pagerCity = clubService.pageClubByPlaceId(cityId, provinceId, seriesId, 1, DEF_CLUBS_NUM_3, 0, 0);
        if(pagerCity != null && !pagerCity.getResultList().isEmpty()) {
        	cityClubs = pagerCity.getResultList();
        	returnClubs.addAll(cityClubs);
        }
        
        //如果市小于3个，查省的
        if (returnClubs.isEmpty() || returnClubs.size() < DEF_CLUBS_NUM_3) {
        	try {
        		proClubs = clubService.pageClubByPlaceId(0, provinceId, seriesId, 1, DEF_CLUBS_NUM_3 - returnClubs.size(), cityId, 0).getResultList();
        		returnClubs.addAll(proClubs);
        	}catch (Exception exception) {
        		exception.printStackTrace();
        	}
        }
        
        //如果省小于3个，查全国的
        if (returnClubs.isEmpty() || returnClubs.size() < DEF_CLUBS_NUM_3) {
        	try {
        		counClubs = clubService.pageClubByPlaceId(0, 0, seriesId, 1, DEF_CLUBS_NUM_3 - returnClubs.size(), cityId, provinceId).getResultList();
        		returnClubs.addAll(counClubs);
        	}catch(Exception exception) {
        		exception.printStackTrace();
        	}
        }
        
        // 组装推荐车友会属性列表
        for(Club club : returnClubs) {
        	JSONObject json = new JSONObject();
            json.put("clubId", club.getClubId());
            json.put("name",xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getName()) : club.getName());
            json.put("logo",xssEncode > 0 ? EncodeUtils.encodeForHTMLFilterNull(club.getLogo()) : club.getLogo());
            json.put("url", systemConfig.getWapRoot() + "/" + club.getClubUrl() + "/");
            int count = memberService.countMembersByClubId(club.getClubId());
            json.put("memeberCount", count);
            json.put("cityName", club.getCityName());
            json.put("provinceName", club.getProvinceName());
            json.put("seriesName", club.getSeriesName());
            json.put("level", club.getLevelId());
            ClubPetrol clubPetrol = petrolService.getValidPetrol(club.getClubId());
            json.put("petrol", clubPetrol == null ? 0 : clubPetrol.getTotalPetrol());
            jsonArray.add(json);
        }
        // 返回车友会列表
        jsonObject.put("data", jsonArray);
        AppControllerStatic.printSuccessMsg(response, jsonObject, callback,
        		AppControllerStatic.V1_VERSION_LATEST);
    }
}
